//
//  APPLEStatusListViewModel.swift
//  123
//
//  Created by pangjiaxing on 16/1/2.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
import SDWebImage

class APPLEStatusListViewModel: NSObject {
    var statuses : [APPLEStatusViewModel]?
    
    func loadData(isPullUp:Bool, completion:(isSecessed:Bool)->()){
        
        var maxId :Int64 = 0
        var sinceId :Int64 = 0
        
        if isPullUp{
            maxId = statuses?.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else{
            sinceId = statuses?.last?.status?.id ?? 0
        }
        
        APPLENetworkTools.sharedTools.loadStatuses(APPLEUserAccountViewModel.sharedViewModel.accessToken!, maxId: maxId, sinceId: sinceId) { (response, error) -> () in
            if error != nil {
                print(error)
                completion(isSecessed: false)
                return
            }
            
            guard let responseDict = response as? [String:AnyObject] else{
                completion(isSecessed: false)
                print("返回的不是字典")
                return
            }
            
            //           print(responseDict)
            
            let statusDicts = responseDict["statuses"]as![[String:AnyObject]]
            
            var tempArray :[APPLEStatusViewModel] = [APPLEStatusViewModel]()
            
            
            if self.statuses == nil{
                self.statuses = [APPLEStatusViewModel]()
            }
            
            for dict in statusDicts {
                let status = APPLEStatus(dict: dict)
                let statusViewModel = APPLEStatusViewModel()
                statusViewModel.status=status
                tempArray.append(statusViewModel)
            }
            if isPullUp{
                self.statuses! += tempArray
            }else{
                self.statuses = tempArray+self.statuses!
            }
            
            self.cacheSingleImage(tempArray ,completion:completion)
        }
//        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
//        let params=[
//            "access_token":APPLEUserAccountViewModel.sharedViewModel.accessToken!,
//            "max_id": "\(maxId)",
//            "since_id": "\(sinceId)"
//        ]
        
//        APPLENetworkTools.sharedTools.request(urlstring: urlString, paraneter: params) { (response, error) -> () in
//            
//        }
    }
    
    private func cacheSingleImage(dataArray:[APPLEStatusViewModel]?,completion:(isSuccess:Bool)->()){
        var dataLength = 0
        let group = dispatch_group_create()
        for viewModel in dataArray! {
            if viewModel.picUrls?.count != 1{
                continue
            }
            let urlString = viewModel.picUrls?.first?.thumbnail_pic
            let url = NSURL(string: urlString!)
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error,_,_,_) -> Void in
                if image != nil {
                    dataLength += UIImagePNGRepresentation(image)!.length
                }
                dispatch_group_leave(group)
            })
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            completion(isSuccess: true)
        }
    }
}
